import {GetServerSideProps, NextPage} from 'next';
import Head from 'next/head';
import {useRouter} from 'next/router';
import {useEffect, useMemo, useRef, useState} from 'react';
import {Game} from '../../../utils/games';

type GamePageProps = {
  game: Game,
}

const GamePlayPage: NextPage<GamePageProps> = ({
  game,
}) => {
  const router = useRouter();
  const [wrapperWidth, setWrapperWidth] = useState<number>();
  const { id } = router.query;
  const timeoutRef = useRef(null as NodeJS.Timeout | null);

  const aspectRatio = useMemo(() => game.data.aspectRatio, [game]);

  useEffect(() => {
    const handleResize = () => {
      const currentAspectRatio = window.innerWidth / window.innerHeight;
      if (currentAspectRatio > aspectRatio) {
        if (timeoutRef.current) {
          window.clearTimeout(timeoutRef.current);
        }
        timeoutRef.current = setTimeout(() => {
          setWrapperWidth(window.innerHeight * aspectRatio);
        }, 50);
      } else {
        setWrapperWidth(undefined);
      }
    }

    window.addEventListener('resize', handleResize);
    handleResize();
    return () => {
      window.removeEventListener('resize', handleResize);
    }
  }, [aspectRatio]);

  if (id) {
    return (
      <>
        <Head>
          <title>{game.name}</title>
        </Head>
        <div
          style={{
            width: '100%',
            height: '100%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            position: 'fixed',
            top: 0,
            left: 0,
            backgroundColor: 'black',
          }}
        >
          <div
            style={{
              width: wrapperWidth ?? '100%',
              paddingBottom: `${100 / aspectRatio}%`,
              position: 'relative',
            }}
          >
            <object
              style={{
                width: '100%',
                height: '100%',
                position: 'absolute',
                top: 0,
                left: 0,
                objectPosition: 'center',
              }}
            >
              <embed
                src={`/games/${id}/${game.main}`}
                width="100%"
                height="100%"
              />
            </object>
          </div>
        </div>
      </>
    );
  }

  return null;
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const response = await fetch(`http://localhost:3000/api/games/${ctx.query.id}`);
  if (response.status !== 200) {
    return {
      notFound: true,
    }
  }

  const game = await response.json();
  return {
    props: {
      game,
    }
  }
}

export default GamePlayPage;
